//
//  NewMessageViewController.m
//  jungoo
//
//  Created by Sinbad Flyce on 9/19/12.
//  Copyright (c) 2012 VMODEV. All rights reserved.
//

#import "NewMessageViewController.h"
#import "MessagePeopleViewController.h"
#import "Extensions.h"

@implementation NewMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Private Method

- (UITableViewCell*)createTopCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:2];
}

- (void)initAppearance
{
    [self setTitle:@"Messages"];
    [self setBackButtonImageActiveName:@"" 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back)];
    
    [self setRightButtonImageActiveName:@"" 
                           inactiveName:@"edit-button" 
                                 target:self 
                                 action:@selector(edit)];
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg.png"]]];
    [self.tableView setAllowsSelectionDuringEditing:YES];
}

- (UITableViewCell*)createCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:6];
}

- (NSString*)stringFromArray:(NSArray*)aArray
{
    NSMutableArray *items = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aItem in aArray) {
        [items addObject:[aItem objectForKey:@"user_id"]];
    }
    
    return [items componentsJoinedByString:@";"];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

#pragma mark - Action

- (void)edit
{
    
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addPeople
{
    MessagePeopleViewController *mpVC = [[[MessagePeopleViewController alloc] initWithNibName:@"MessagePeopleViewController" 
                                                                                       bundle:nil] autorelease];
    
    [mpVC setDelegate:self];
    [self.navigationController pushViewController:mpVC animated:YES];    
}

- (IBAction)addConversation:(id)sender
{
    if ([dataSource count] == 0) {
        [JGoUtility showAlert:@"You have to add more people to create new a conversation."];
        return;
    }
    
    NSString *textMessage = ((UITextField*)[enterMessageView viewWithTag:1]).text;
    
    if ([textMessage length] == 0) {
        [JGoUtility showAlert:@"You have to enter a message."];
        return;        
    }
    
    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                            target:self
                             title:@"Creating Message..."
                          selector:@selector(delayAddConversation:)];
}

#pragma mark - TableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *aview = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)] autorelease];
    [aview setBackgroundColor:[UIColor clearColor]];
    
    return aview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 48;
    }
    
    return 48;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataSource count] + 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.row == 0)
    {
        cell = [self createTopCellFromNib];
        [[cell buttonWithTag:1] addTarget:self 
                                   action:@selector(addPeople) forControlEvents:UIControlEventTouchUpInside];
    }
    else {
        cell = [self createCellFromNib];
        NSDictionary *aPerson = [dataSource objectAtIndex:indexPath.row - 1];
        NSString *senderId = [aPerson objectForKey:@"user_id"];
        
        [cell titleTextWithTag:2].text = [aPerson objectForKey:@"name"];
        [cell titleTextWithTag:3].text = [aPerson objectForKey:@"university"];
        [cell imageViewWithTag:1].image = [[JGoUtility sharedCachedAvatars] objectForKey:senderId];
        [[cell imageViewWithTag:1] makeBorderRound];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        MessagePeopleViewController *mpVC = [[[MessagePeopleViewController alloc] initWithNibName:@"MessagePeopleViewController" 
                                                                                           bundle:nil] autorelease];
        
        [self.navigationController pushViewController:mpVC animated:YES];
    }
}

#pragma mark - TextField Delegeate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:nil context:NULL];    
    CGRect newRect = CGRectMake(0, 200 - 44, 320, 44);
    enterMessageView.frame = newRect;
    [UIView commitAnimations];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataSource count] - 1
                                                              inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    CGRect newRect = CGRectMake(0, 372, 320, 44);
    enterMessageView.frame = newRect;
    
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    return YES;
}

#pragma mark - People Delegate

- (void)didSelectPeopleToJoinChat:(NSArray *)people
{
    NSLog(@"%@",[people description]);
    [dataSource release];
    dataSource = (id)[people retain];
    [self.tableView reloadData];
}

#pragma mark - Delay Method

- (void)delayAddConversation:(MBProgressHUD*)progress
{
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSError *error = nil;
    NSString *inviteeIds = [self stringFromArray:dataSource];
    NSString *textMessage = ((UITextField*)[enterMessageView viewWithTag:1]).text;
    
    NSDictionary *newConversation = [JGoAPI createConversationWithUserId:userId
                                                        conversationName:textMessage
                                                              inviteeIds:inviteeIds
                                                                   error:&error];
    
    if (!error) {
        
        NSString *nCid = [[newConversation objectForKey:@"data"] objectForKey:@"id"];
        
        [JGoAPI addMessageWithUserId:userId
                      conversationId:nCid
                                type:@"0"
                             content:textMessage
                               error:&error];
        
        if (!error) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
    if (error) {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}

@end
